package com.lz.yz.member.service.impl;

import com.github.pagehelper.PageHelper;
import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.core.AbstractService;
import com.lz.yz.member.dao.AttentionsMapper;
import com.lz.yz.member.entity.Attentions;
import com.lz.yz.member.model.AttentionsModel;
import com.lz.yz.member.param.AttentionsParam;
import com.lz.yz.member.service.AttentionsService;
import com.lz.yz.outing.service.SyncLockService;
import com.util.common.Page;
import com.util.common.QueryList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * Created by CodeGenerator on 2017/11/09.
 */
@Service
@Transactional
public class AttentionsServiceImpl extends AbstractService<Attentions> implements AttentionsService {
    @Resource
    AttentionsMapper attentionsMapper;

    @Autowired
    SyncLockService syncLockService;


    @Override
    public ReturnValue insert(AttentionsModel model) {
        if (model.getTargetId()==null) {
            return ReturnValue.generateFalseReturnValue("targetId cannot be null");
        }
        Integer accountId = model.getAccountId();
        if (!syncLockService.syncLock("attention//" + accountId, 1, TimeUnit.SECONDS)) {
            return ReturnValue.generateFalseReturnValue("请不要频繁点击!");
        }
        if (accountId.equals(model.getTargetId())) {
            return ReturnValue.generateFalseReturnValue("不能关注自己!");
        }

        //查询用户对被关注对象的关系
        Attentions attentions = attentionsMapper.isAttentions(new AttentionsParam(accountId, model.getTargetId(),0,0));
        if (attentions == null) {
            //添加关注
            attentions = new Attentions();
            attentions.setAccountId(accountId);
            attentions.setTargetId(model.getTargetId());
            attentionsMapper.insert(attentions);
            return ReturnValue.generateTrueReturnValue("添加关注成功!",true);
        } else {
            //取消关注
            attentions.setDeletedAt(new Date());
            this.update(attentions);
            return ReturnValue.generateTrueReturnValue("取消关注成功!",false);
        }
    }

    @Override
    public ReturnValue listAttentions(AttentionsParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Attentions> memberAttentions = attentionsMapper.queryMemberAttentions(param);
        QueryList<AttentionsModel> queryList = new QueryList(memberAttentions, Page.toPage(memberAttentions));
        return ReturnValue.generateTrueReturnValue(queryList);
    }
}
